package service

import (
	"duoke/model"
	"duoke/tables"
	"duoke/utils/orm"
	"github.com/gin-gonic/gin"
)

var SeparateGroup = new(separateGroupService)

type separateGroupService struct{}

func (s *separateGroupService) Save(c *gin.Context, req model.ReqSeparateGroup) error {
	accountR, _ := Request.Account(c)
	if req.Id > 0 {
		// 保存数据
		_, err := orm.Db.ID(req.Id).Where("acid =?", accountR.Id).Update(req)
		if err != nil {
			return err
		}
	} else {
		// 保存数据
		req.Acid = accountR.Id
		_, err := orm.Db.Insert(req)
		if err != nil {
			return err
		}
	}
	return nil
}

func (s *separateGroupService) Page(c *gin.Context, req model.ReqList) ([]model.SeparateGroupList, int64, error) {
	accountR, _ := Request.Account(c)
	// 分页
	list := make([]model.SeparateGroupList, 0)
	offset := (req.PageNo - 1) * req.PageSize
	query := orm.Db.Desc("id")
	query.Where("acid = ?", accountR.Id)
	if req.Keyword != "" {
		query = query.Where("name like ?", "%"+req.Keyword+"%")
	}
	//判断子账户
	total, err := query.Limit(req.PageSize, offset).FindAndCount(&list)
	if err != nil {
		return nil, 0, err
	}
	return list, total, nil
}

func (s *separateGroupService) Del(c *gin.Context, req model.ReqId) error {
	accountR, _ := Request.Account(c)
	_, err := orm.Db.ID(req.Id).Where("acid =?", accountR.Id).Delete(new(tables.SeparateGroup))
	if err != nil {
		return err
	}
	return nil
}
